package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name) {
        log.info("菜品分页查询 page:" + page + " pageSize:" + pageSize + " name:" + name);
        //设置分页
        Page<Dish> dishPage = new Page<>(page, pageSize);
        //设置查询条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(name != null, Dish::getName, name)
                .orderByAsc(Dish::getSort)
                .orderByAsc(Dish::getUpdateTime);
        //查询
        dishService.page(dishPage, wrapper);


        //        1. IPage<DishDto>
        IPage<DishDto> dishDtoPage = new Page<>(page, pageSize);
//        2. 分页基本数据：当前页、总条数...
//        对象copy（本质getter/setter）  参数：源对象、目标对象、忽略的属性
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
//        3. records中的数据:
        List<Dish> records = dishPage.getRecords();
        List<DishDto> dishDtoList = records.stream().map(item -> {//item=dish
            DishDto dishDto = new DishDto();
//                   dish基本数据：name id image...
            BeanUtils.copyProperties(item, dishDto);
//                  categoryName? 通过cid 去查询name
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();

            dishDto.setCategoryName(categoryName);
//                    收集成新的集合
            return dishDto;
        }).collect(Collectors.toList());

//        4. 封装好的这个数据集合要放到IPage<DishDto>  records上
        dishDtoPage.setRecords(dishDtoList);
//        0.4返回数据
        return R.success(dishDtoPage);
    }

    /**
     * 添加新菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R save(@RequestBody DishDto dishDto) {
        log.info("添加新菜品:" + dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        System.out.println("------------------------------------------------------------------------------------------------");
        System.out.println(dishDto.getCategoryId());
        System.out.println("------------------------------------------------------------------------------------------------");

        // 清理缓存(全清理)(清理指定缓存)
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("成功");
    }

    /**
     * 根据id菜品删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R delete(@RequestParam List<Long> ids) {
        log.info("根据id菜品删除:" + ids.toString());
        boolean b = dishService.deleteByIdsWithFlavor(ids);
        return b ? R.success("成功") : R.error("失败");
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id) {
        log.info("根据id查询菜品:" + id);
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        if (dishDto != null) {
            return R.success(dishDto);
        }
        return R.error("失败");
    }

    /**
     * 根据id修改菜品信息
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R update(@RequestBody DishDto dishDto) {
        log.info("根据id修改菜品信息:" + dishDto.toString());
        boolean b = dishService.updateWithFlavor(dishDto);

        // 清理缓存
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);

        return b ? R.success("成功") : R.error("失败");
    }

    /**
     * 更改菜品的售卖状态
     *
     * @param ids
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    public R updateStatus(@RequestParam List<Long> ids, @PathVariable Integer status) {
        log.info("更改菜品" + ids.toString() + "的售卖状态为:" + status);
        UpdateChainWrapper<Dish> wrapper = dishService.update();
        boolean b = wrapper.in("id", ids).set("status", status).update();
        return b ? R.success("成功") : R.error("失败");
    }

    /**
     * 根据'分类id'或者'菜名'查询在售的菜品列表
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R getByCategoryId(Dish dish) {
        log.info("根据'分类id'或者'菜名'查询在售的菜品列表:{}", dish);
        List<DishDto> dishDtos = new ArrayList<>();
        //定义一个key
        String key = "dish_"+dish.getCategoryId()+"_1";
        //从缓存中获取数据
        Object o = redisTemplate.opsForValue().get(key);
        if(o!=null){
            dishDtos = (List<DishDto>) o;
            return R.success(dishDtos);
        }
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //设置查询条件
        wrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
                .like(dish.getName() != null, Dish::getName, dish.getName())
                //添加条件，查询状态为1（起售状态）的菜品
                .eq(Dish::getStatus, 1)
                //添加排序条件
                .orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(wrapper);

        // 用dishDto进行封装
        dishDtos = list.stream().map(item -> {
            //基本字段拷贝
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //categoryName赋值
            Category category = categoryService.getById(item.getCategoryId());
            if(category!=null){
                dishDto.setCategoryName(category.getName());
            }
            //口味flavors赋值
            LambdaQueryWrapper<DishFlavor> dishFlavorWrapper = new LambdaQueryWrapper<>();
            dishFlavorWrapper.eq(DishFlavor::getDishId,item.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorWrapper);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());

        //存入redis缓存(对象-->json)(jdk序列化器)(entity实现序列化器)
        redisTemplate.opsForValue().set(key,dishDtos,10, TimeUnit.MINUTES);

        return R.success(dishDtos);
    }

}
